package sklep;

import java.lang.String;
import java.lang.Integer;
import java.lang.Float;
import java.util.Hashtable;
import java.util.Enumeration;
import javax.servlet.http.*;

public class Koszyk {

  protected Hashtable<String,String[]> items = new Hashtable<String,String[]>();

  public void addItem(String itemId,String product_name, float price, int quantity) {
    String[] item = {itemId, product_name, Float.toString(price),
    Integer.toString(quantity)};

    if (items.containsKey(itemId)) {

      String[] tmpItem = (String[])items.get(itemId);
      int tmpQuant = Integer.parseInt(tmpItem[3]);
      quantity += tmpQuant;
      tmpItem[3] = Integer.toString(quantity);
    }
    else {
      items.put(itemId, item);
    }
  }

  public void removeItem(String itemId) {
    if (items.containsKey(itemId)) {
    	 String[] tmpItem = items.get(itemId);
    	 if(Integer.parseInt(tmpItem[3]) > 1)
    	 {
    		 tmpItem[3] = Integer.toString(Integer.parseInt(tmpItem[3]) - 1);
    		 items.put(itemId, tmpItem);
    	 }
    	 else
    	 {
    		 items.remove(itemId);
    	 }
    	 
    }
  }
  public void updateQuantity(String itemId, int quantity) {
    if (items.contains(itemId)) {
      String[] tmpItem = items.get(itemId);
      tmpItem[3] = Integer.toString(quantity);
    }
  }

  public Enumeration<String[]> getEnumeration() {

    return items.elements();
  }

  public float getCost() {

    Enumeration<String[]> e = items.elements();
    String[] tmpItem;
    float totalCost = 0.00f;

    while (e.hasMoreElements()) 
    {
    	tmpItem = e.nextElement();
    	totalCost += (Float.parseFloat(tmpItem[3]) * Float.parseFloat(tmpItem[2]));
    }
    return totalCost;
  }

  public int getNumOfItems() {

    Enumeration<String[]> e = items.elements();
    String[] tmpItem;
    int numOfItems = 0;

    while (e.hasMoreElements()) {

      tmpItem = e.nextElement();
      numOfItems += Integer.parseInt(tmpItem[3]);
    }

    return numOfItems;
  }
  
  public void checkRequest(HttpServletRequest request)
  {
	  String id = request.getParameter("id");
	  	
	    if ( id != null ) {
	    	String submit = request.getParameter("Submit");
	    	if(submit.equals("Add"))
	    	{
	    		String product_name = request.getParameter("product_name");
	          	Float price = new Float(request.getParameter("price"));          
	          	addItem(id, product_name, price.floatValue(), 1);
	    	}
	    	else if(submit.equals("Remove"))
	    	{
	    		removeItem(id);
	    	}
	    }
  }
  
  public int checkBuy(HttpServletRequest request)
  {
	  String buy = request.getParameter("Buy");
	  if(buy != null)
	  {
		  int numberOfItems = this.getNumOfItems();
		  items.clear();
		  return  numberOfItems;
	  }
	  return 0;
  }
}
